<?php

use EasyWeChat\OpenPlatform\Server\Guard;


class AuthController extends WxBaseController
{
    /**
     * 授权事件接收
     */
    public function getAction()
    {
        try{
        if ($this->request->isPost()) {
            MyLog::setLog($_REQUEST, '微信数据', "", "", "json", LOG_PATH . "/" . "WeChat/" . date("Ymd") . "_push.log");
            $server = self::$open->server;
            // 处理授权成功事件
            $server->push(function ($message) {
                $authorize = AuthorizedApp::findFirst("app_id='{$message['AuthorizerAppid']}'");
                if (!$authorize) {
                    $authorize = new AuthorizedApp();
                    $authorize->app_id = $message['AuthorizerAppid'];
                }
                $authorize->authorized_time = date("Y-m-d H:i:s");
                $authorize->enabled = 1;
                $authorize->update_time = date("Y-m-d H:i:s");
                $authorize->save();

                //获取基本信息
                $this->upInfo($message['AuthorizerAppid']);
                $this->add_task($message['AuthorizerAppid']);

            }, Guard::EVENT_AUTHORIZED);

            // 处理授权更新事件
            $server->push(function ($message) {
                $authorize = AuthorizedApp::findFirst("app_id='{$message['AuthorizerAppid']}'");
                if (!$authorize) {
                    $authorize = new AuthorizedApp();
                    $authorize->app_id = $message['AuthorizerAppid'];
                }
                $authorize->authorized_time = date("Y-m-d H:i:s");
                $authorize->enabled = 1;
                $authorize->update_time = date("Y-m-d H:i:s");
                $authorize->save();
            }, Guard::EVENT_UPDATE_AUTHORIZED);

            // 处理授权取消事件
            $server->push(function ($message) {
                $authorize = AuthorizedApp::findFirst("app_id='{$message['AuthorizerAppid']}'");
                if (!$authorize) {
                    $authorize = new AuthorizedApp();
                    $authorize->app_id = $message['AuthorizerAppid'];
                }
                $authorize->authorized_time = date("Y-m-d H:i:s");
                $authorize->enabled = 0;
                $authorize->update_time = date("Y-m-d H:i:s");
                $authorize->save();

                $this->redis->delete('ww:refresh:token:' . $message['AuthorizerAppid']);

            }, Guard::EVENT_UNAUTHORIZED);

            $server->serve()->send();
            $this->view->disable();
        } else {

            echo "<a id = 'a' href='" . self::$site . "/auth/authorize" . "'></a>";
            echo "<script>
let a= document.getElementById('a')
a.click()
</script>";
            die();
        }
        }catch (Exception $e){
            print_r($e->getMessage());die;
            file_put_contents(LOG_PATH."/".date("ymd")."_weixin.log",print_r([$_REQUEST,$e->getMessage(),$e->getFile()],1));
        }
    }

    /**
     * 授权页面
     * 为了防止授权出错
     */
    public function authorizeAction()
    {
        $url = self::$open->getPreAuthorizationUrl(self::$site . '/auth/callback');

        header('Location: ' . $url);
        die();
    }

    /**
     * 授权回调
     */
    public function callbackAction()
    {
        $authCode = $this->request->get('auth_code');
        $expiresIn = $this->request->get('expires_in');

        if (empty($authCode) || empty($expiresIn)) {
            $this->exitMessage(false, '参数错误');
        } else {
            $auth = self::$open->handleAuthorize($authCode);
            if (isset($auth["authorization_info"]) && !empty($auth["authorization_info"])) {
                $appInfo = $auth["authorization_info"];
                $appId = $appInfo["authorizer_appid"];
                $accessToken = $appInfo["authorizer_access_token"];
                $expiresIn = $appInfo["expires_in"];
                $refreshToken = $appInfo["authorizer_refresh_token"];
                $author = AuthorizedApp::findFirst("app_id='{$appId}'");
                if (!$author) {
                    $author = new AuthorizedApp();
                    $author->app_id = $appId;
                }
                $author->access_token = $accessToken;
                $author->expires_in = $expiresIn;
                $author->refresh_token = $refreshToken;
                $author->save();

                $this->exitMessage(true, '授权成功');
            } else {
                $this->exitMessage(false, '发生错误，请稍后重试');
            }
        }
        $this->view->disable();
    }

    /**
     * 更新公众号信息
     * @param $appId
     */
    private function upInfo($appId)
    {
        $info = self::$open->getAuthorizer($appId);
        $info = $info['authorizer_info'];
        $nick_name = $info['nick_name'];
        $head_img = $info['head_img'];
        $service_type_info = $info['service_type_info']['id'];
        $verify_type_info = $info['verify_type_info']['id'];
        $raw_id = $info['user_name'];
        $principal_name = $info['principal_name'];
        $alias = $info['alias'];
        $qrcode_url = $info['qrcode_url'];
        $type = '测试';

        $sql = "INSERT INTO authorized_app_info ( `app_id`, `nick_name`, `head_img`, `service_type_info`, `verify_type_info`, `raw_id`, `principal_name`, `alias`, `qrcode_url`, `type`)
VALUES
	( '{$appId}', '{$nick_name}', '{$head_img}', '{$service_type_info}', '{$verify_type_info}', '{$raw_id}', '{$principal_name}', '{$alias}', '{$qrcode_url}','{$type}') ON DUPLICATE KEY UPDATE `nick_name` = '{$nick_name}',
	`head_img` = '{$head_img}',
	`service_type_info` = '{$service_type_info}',
	`verify_type_info` = '{$verify_type_info}',
	`raw_id` = '{$raw_id}',
	`principal_name` = '{$principal_name}',
	`alias` = '{$alias}',
	`qrcode_url` = '{$qrcode_url}',`type` = '{$type}';";
//        MyLog::setLog([$sql], "shouquan", Logger::INFO, '', '', PUBLIC_PATH . '/log/sub_msg/' . "cs_sub_msg_new_task_error.log");
        $this->db->execute($sql);
    }


    private function add_task($appId){
        $task=New TaskFans();
        $task->app_id=$appId;
        $task->status=0;
        $task->result=0;
        $task->save();
    }
}

